#include <stdio.h>
#include <stdlib.h>
// #include <string.h>
#include <unistd.h>

#include <lib/Log/include/Log.h>
#include <SocketUtils.h>

#include <FinalCType/List.h>
#include <FinalCType/String.h>
#include <FinalCType/StringList.h>

#include <errno.h>

FinalC_Object_Define(User) {
    char username[100];
};

int	main(int argc, char **argv) {
    
    TcpSocket tcp = {0};
    // UdpSocketOrigin origin = {0};

    User user = {0};
    if (argc > 3) {
        strcat(user.username, argv[3]);
    } else {
        strcat(user.username, "未知用户");
    }

    if (createTcpSocketWithHostPort(&tcp, "localhost", 8080)
            && socketConnect(&tcp, &tcp.address, sizeof(tcp.address))) {
        
        INFO_LOG("连接服务器成功.");
        INFO_LOG("您当前的用户名为: %s", user.username);

        // String *msg = createStringWith_copy_cstr("connect::::");
        // stringAppend_cstr(msg, user.username);
        // udpSocketWrite(&tcp, msg->value, msg->len, &origin);

        bool connected = false;

        if (!connected) {
            char msg[1000] = {"connect::::"};
            strcat(msg, user.username);
            tcpSocketWrite(&tcp, msg, sizeof(msg));
            tcpSocketRead(&tcp, msg, sizeof(msg));
            // INFO_LOG("%s", msg);
            connected = true;
        }

        while (1)
        {
            fd_set fds;
            FD_ZERO(&fds);
            FD_SET(STDIN_FILENO, &fds);
            FD_SET(tcp.socket, &fds);

            int ret = select(tcp.socket+1, &fds, NULL, NULL, NULL);

            if (ret > 0) {
                // 输入消息息 -> 发送消息
                if (FD_ISSET(STDIN_FILENO, &fds)) {
                    // char buffer[1000];
                    String *buffer = createStringWith_size(1000);

                    scanf("%s", buffer->value);

                    if (strncmp(buffer->value, "/name",5) == 0) {
                        memset(user.username, 0, 100);
                        strcat(user.username, buffer->value);
                        INFO_LOG("设置用户名称为: %s", user.username);

                        deleteString(buffer);
                        continue;
                    } 

                    if (strncmp(buffer->value, "/connect", 9) == 0) {
                        if (!connected) {
                            char msg[1000] = {"connect::::"};
                            strcat(msg, user.username);
                            INFO_LOG("尝试连接服务器");

                            tcpSocketWrite(&tcp, msg, sizeof(msg));
                            tcpSocketRead(&tcp, msg, sizeof(msg));
                            connected = true;
                        } else {
                            deleteString(buffer);
                            continue;
                        }
                    }

                    if (connected) {
                        String *message = createStringWith_copy_cstr("msg::::");
                        message = stringAppend_cstr(message, user.username);
                        message = stringAppend_cstr(message, "::::");
                        message = stringAppend(message, buffer);
                        // message

                        tcpSocketWrite(&tcp, message->value, message->len);
                        INFO_LOG("发送消息: %s", message->value);
                        
                        deleteString(message);
                    }

                    // 释放 buffer
                    deleteString(buffer);
                }

                // 新消息
                if (FD_ISSET(tcp.socket, &fds)) {

                    String *buffer = createStringWith_size(1000);
                    // UdpSocketOrigin origin = {0};
                    int len;
                    tcpSocketRead(&tcp, buffer->value, buffer->len);
                    if ((len = tcpSocketRead(&tcp, buffer->value, buffer->len)) == 0) {
                        INFO_LOG("%s", strerror(errno));
                        close(tcp.socket);
                        ERROR_LOG("Socket 已断开连接");
                        // continue;
                    }

                    // INFO_LOG("收到新消息: %s", len ,buffer->value);

                    // 消息解读: 格式 msg::::user::::value
                    if (stringContains_cstr(buffer, "msg::::")) {
                        const char *sp = "::::";
                        StringList *words = createStringListWithSplits(buffer, sp);

                        int cnt = stringListLength(words);
                        INFO_LOG("%s:%s", 
                            stringListIndex(words, 1)->string->value,
                            stringListIndex(words, 2)->string->value); 
                        deleteStringList(words);
                    }

                    // 释放 buffer
                    deleteString(buffer);
                }
            }
        }
    } else {
        WARNING_LOG("服务器 %s:%s 连接失败.", argv[1], argv[2]);
    }

    INFO_LOG("error");

    return 0;
}